package com.jsz.peini.server.thread;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.log4j.Logger;

import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserInfoExample;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.SpringContextUtil;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.redis.util.UserRedisUtil;
import com.jsz.peini.service.user.UserInfoService;
import com.jsz.peini.vo.UserVo;


public class CreditUpdateThread extends Thread{
	
	Logger logger = Logger.getLogger(CreditUpdateThread.class);
	
	private UserInfoMapper userInfoMapper;
	
	private UserInfoService userInfoService;
	
	public void init(){
		this.start();
	}
	
	@Override
	public void run() {
		super.run();
		
		userInfoMapper = (UserInfoMapper)SpringContextUtil.getBean(UserInfoMapper.class);
		userInfoService = (UserInfoService)SpringContextUtil.getBean(UserInfoService.class);
		
		while(true)
		{
			try {
				Integer cnt = PeiniUtils.creditUpdateList.take();
				UserInfoExample userExample = new UserInfoExample();
				userExample.createCriteria().andIntegrityListGreaterThan(0);
				List<UserInfo> useList = userInfoMapper.selectByExample(userExample);
				
				List<LinkedHashMap<String,Object>> rankList = userInfoService.getRank(1, 3);
				
				for (UserInfo userInfo : useList) {
					UserInfo u = new UserInfo();
					u.setId(userInfo.getId());					
					u.setIntegrityList(0);
					//userInfoMapper.updateByPrimaryKey(userInfo);
					userInfoMapper.updateByPrimaryKeySelective(u);
					
					//更新缓存
					UserVo userVo = UserRedisUtil.getUserVoByUserId(userInfo.getId());
					userVo.setIntegrityList(new BigDecimal("0"));
					UserRedisUtil.addUserToRedis(userVo);
				}
				for (int i = 0; i < rankList.size(); i++) {
					LinkedHashMap<String,Object> rank = rankList.get(i);
					UserInfo uInfo = new UserInfo();
					uInfo.setId(rank.get("userId").toString());
					uInfo.setIntegrityList(i+1);
					userInfoMapper.updateByPrimaryKeySelective(uInfo);
					
					//更新缓存
					UserVo userVo = UserRedisUtil.getUserVoByUserId(rank.get("userId").toString());
					if(userVo != null){
						userVo.setIntegrityList(new BigDecimal(i+1));
						UserRedisUtil.addUserToRedis(userVo);
					}
				}
				
				Thread.sleep(1);
			} catch (Exception e1) {
				e1.printStackTrace();
				logger.info("fail", e1);
			}
		}
		
	}
	
}